import { Module } from '@nestjs/common';
import { PublicResourceService } from './public_resource.service';
import { PublicResourceController } from './public_resource.controller';
import { MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import * as fs from 'fs';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PublicResource } from './entities/public_resource.entity';
import { ImagerasterModule } from 'src/imageraster/imageraster.module';

@Module({
  imports: [
    MulterModule.register({
      storage: diskStorage({
        destination: function (req, fileName, callback) {
          try {
            let folder = 'other'; // 默认文件夹名
            if (fileName.mimetype.startsWith('image/')) {
              if (fileName.mimetype === 'image/tiff') {
                folder = 'imageraster';
              } else {
                folder = 'image';
              }
            } else if (fileName.mimetype.startsWith('audio/')) {
              folder = 'audio';
            } else if (fileName.mimetype.startsWith('video/')) {
              folder = 'video';
            } else if (fileName.mimetype.startsWith('text/')) {
              folder = 'text';
            } else if (fileName.mimetype.startsWith('application/')) {
              folder = 'application';
            }
            const destinationPath = `${process.env.FILE_PATH}/public/${folder}`;
            if (!fs.existsSync(destinationPath)) {
              fs.mkdirSync(destinationPath, { recursive: true });
            }
            callback(null, destinationPath);
          } catch (error) {
            console.error(`Error in setting file destination:`, error);
          }
        },
        filename: (_, file, callback) => {
          const fileName = Buffer.from(file.originalname, 'latin1').toString(
            'utf8',
          );
          return callback(null, fileName);
        },
      }),
    }),
    TypeOrmModule.forFeature([PublicResource]),
    ImagerasterModule,
  ],
  controllers: [PublicResourceController],
  providers: [PublicResourceService],
  exports: [PublicResourceService],
})
export class PublicResourceModule {}
